package com.steven.ourcontest.forum.viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.steven.ourcontest.base.BaseViewModel
import com.steven.ourcontest.forum.api.ForumApi
import com.steven.ourcontest.forum.bean.DiscussInfoList
import com.steven.ourcontest.forum.bean.ForumInfo
import com.steven.ourcontest.forum.bean.ForumInfoList
import com.steven.ourcontest.information.api.InfoApi
import com.steven.ourcontest.net.EmptyResponse
import com.steven.ourcontest.utils.plusAssign
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers

class ForumDiscussViewModel : BaseViewModel() {
    private val _forumInfo = MutableLiveData<ForumInfo?>()
    val forumInfo: LiveData<ForumInfo?>
        get() = _forumInfo

    private val _discussInfoList = MutableLiveData<DiscussInfoList?>()
    val discussInfoList: LiveData<DiscussInfoList?>
        get() = _discussInfoList

    private val _addDiscussRes = MutableLiveData<EmptyResponse?>()
    val addDiscussRes: LiveData<EmptyResponse?>
        get() = _addDiscussRes

    fun queryForumByFid(
        page: Long,
        onSuccess: (() -> Unit)? = null,
        onError: ((throwable: Throwable) -> Unit)? = null
    ) {
        disposed += ForumApi.instance.queryForumByFid(page)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                _forumInfo.value = it.result
                onSuccess?.invoke()
            }, {
                it.printStackTrace()
                onError?.invoke(it)
            })
    }

    fun queryDiscussList(
        forumId: Long,
        onSuccess: (() -> Unit)? = null,
        onError: ((throwable: Throwable) -> Unit)? = null
    ) {
        disposed += ForumApi.instance.queryDiscussList(forumId)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                _discussInfoList.value = it.result
                onSuccess?.invoke()
            }, {
                it.printStackTrace()
                onError?.invoke(it)
            })
    }

    fun addDiscuss(forumId: Long,content:String){
        disposed += ForumApi.instance.addDiscuss(forumId,content)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                _addDiscussRes.value = it.result
            }, {
                it.printStackTrace()
            })
    }

    fun addHistory(fid: Long){
        disposed += ForumApi.instance.addHistory(fid)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
            }, {
                it.printStackTrace()
            })
    }
}